use std::{io::prelude::*, path::PathBuf};
use std::fs;
use structopt::StructOpt;
use std::error::Error;
use csv::ReaderBuilder;

#[derive(Debug, StructOpt)]
#[structopt(name = "csv2arb", version = "0.1.0", about = "Change Arb Wave .csv file to .arb file.")]
struct Arguments {
    /// Input csv file
    #[structopt(short, parse(from_os_str))]
    csv: PathBuf,

    /// Output arb file, <arbwave.arb> default
    #[structopt(short, parse(from_os_str))]
    arb: Option<PathBuf>,

    // /// Enable verbose output
    // #[structopt(short, long)]
    // verbose: bool
}

fn main() -> Result<(), Box<dyn Error>> {
    let mut ifile = std::path::PathBuf::from("");
    let mut ofile = std::path::PathBuf::from("");

    let args = Arguments::from_args();
    ifile = args.csv;
    ofile = match args.arb {
        Some(o) => o,
        _ => std::path::PathBuf::from("arbwave.arb"),
    };

    let mut ampls: Vec<f32> = Vec::new();
    let mut rdr = ReaderBuilder::new().from_path(ifile).unwrap();
    for result in rdr.records() {
        let record = result.unwrap();
        let amp: f32 = record.get(1).unwrap().parse().unwrap();
        ampls.push(amp);
    }

    let arb_wave_len: u32 = ampls.len() as u32;
    println!("Wave length: {}", arb_wave_len);

    let mut max_amp = ampls[0];
    for amp in &ampls {
        if *amp > max_amp {
            max_amp = *amp;
        }
    }
    let mut min_amp = ampls[0];
    for amp in &ampls {
        if *amp < min_amp {
            min_amp = *amp;
        }
    }
    println!("Max: {}; Min: {}", max_amp, min_amp);

    println!("Output: {:?}", ofile);
    let mut arb_file = fs::File::create(ofile).unwrap();

    let _ = arb_file.write(b" arb").unwrap();
    let _ = arb_file.write(&arb_wave_len.to_le_bytes()).unwrap();
    for ampl in &ampls {
        let _ = arb_file.write(&ampl.to_le_bytes()).unwrap();
    }
    println!("Complete.");

    Ok(())
}
